﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace WinApp.Services.Common
{
    public static class Tools
    {

        public static string HttpGet(string url, Encoding ecoding = null)
        {
            try
            {
                Uri uri = new Uri(url);

                //绕开HTTPS验证（https有可能报错：（基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系））
                if (uri.Scheme.ToLower() == "https")
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
                    {
                        return true;
                    };
                }

                WebRequest request = WebRequest.Create(url);
                request.Headers.Add("Sec-WebSocket-Protocol", "{'Authorization': '4f52f26643d647b9b6a4e94c1147f9c2'}");

                using (WebResponse response = request.GetResponse())
                using (Stream datastream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(datastream, ecoding ?? Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }

            }
            catch (Exception ex)
            {
                return "";
            }
        }

        //for testing purpose only, accept any dodgy certificate... 
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static void Log(Exception ex)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "applog", DateTime.Now.ToString("yyyyMMdd") + ".txt");

            var fileInfo = new FileInfo(path);
            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            using (var stream = fileInfo.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
            {
                writer.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                writer.Write('：');
                writer.Write(ex.Message);
                writer.WriteLine();
                writer.Write("StackTrace：");
                writer.WriteLine(ex.StackTrace);
                writer.WriteLine();
                writer.Close();
            }
        }
    }
}
